package com.itunion.ddd.common.exception;


import com.itunion.ddd.common.base.constant.BaseCode;
import com.itunion.ddd.common.base.constant.BaseResponse;
import com.itunion.ddd.common.exception.framework.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public BaseResponse<Object> handleCustomException(CustomException customException) {
        if (customException == null) {
            return new BaseResponse<>(BaseCode.unknown.getCode(), BaseCode.unknown.getDesc());
        }
        return new BaseResponse<>(customException.getCode(), customException.getMsg(),customException.getResult());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public BaseResponse<Object> handleCustomException(Exception e) {
        log.info("内部服务器错误,{}",e);
        if (e instanceof CustomException){
            CustomException exception = (CustomException)e;
            return new BaseResponse<>(exception.getCode(), exception.getMsg(),exception.getResult());
        }
        return new BaseResponse<>(BaseCode.unknown.getCode(), BaseCode.unknown.getDesc(),e.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResponse<Object> handle2(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();
        if(bindingResult!=null){
            if(bindingResult.hasErrors()){
                FieldError fieldError = bindingResult.getFieldError();
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                log.error(ex.getMessage(),ex);
                return new BaseResponse(BaseCode.PARAM_IS_INVALID.getCode(),defaultMessage,field);
            }else {
                log.error(ex.getMessage(),ex);
                return new BaseResponse(BaseCode.PARAM_IS_INVALID.getCode(),BaseCode.PARAM_IS_INVALID.getDesc(),ex.getMessage());
            }
        }else {
            log.error(ex.getMessage(),ex);
            return new BaseResponse(BaseCode.PARAM_IS_INVALID.getCode(),BaseCode.PARAM_IS_INVALID.getDesc(),ex.getMessage());
        }
    }
}


